Action.frame = (function(){
    var targetImg = null,
        decoImgSelector = null;
    function init(){
        $("#toolBox>div>div:nth-of-type(6) img").click(addFrame);
    }

    function addFrame(event){
        targetImg = event.target;
        frameSelector = new Action.widget.Selector({
            customRender : addFrameImg,
            afterResize : afterResize,
            imgsrc : event.target.src,
            width : PP.w,
            height : PP.h,
            x : PP.x,
            y : PP.y
        });
        $("#canvasBox>canvas").click(mergeImg);
    }
    function addFrameImg(){
        $('<img src="'+this.config.imgsrc+'" width="'+this.width+'" height="'+this.height+'" border="none"/>').appendTo(this.contentDom);
    }

    function afterResize(){
        var img = $("img",this.contentDom)[0];
        img.width = this.width;
        img.height = this.height;
    }

    function mergeImg(){
        if(targetImg && frameSelector){
            var fx = frameSelector.left,
                fy = frameSelector.top,
                fw = frameSelector.width,
                fh = frameSelector.height,
                px = PP.x,
                py = PP.y,
                pw = PP.w,
                ph = PP.h;
            var cx = document.createElement("canvas");
            cx.width = fw;
            cx.height = fh;
            (cx.getContext("2d")).drawImage(targetImg,0,0,fw,fh);

            var sx = fx > px ? 0 : (px-fx),
                dx = fx > px ? fx : px,
                sy = fy > py ? 0 : (py-fy),
                dy = fy > py ? fy : py,
                sw = (fx+fw) > (px+pw) ? (px+pw-dx) : (fx+fw-dx),
                sh = (fy+fh) > (py+ph) ? (py+ph-dy) : (fy+fh-dy);
            PP.context.drawImage(cx, sx, sy, sw, sh, dx, dy, sw, sh);
            $(frameSelector.contentDom).parent().remove();
        }
    }

    return {
        init : init
    }
})();